package TalkChat;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetSocketAddress;

public class TalkSender implements Runnable{
    DatagramSocket socket= null;
    BufferedReader reader=null;

    private int fromPort;
    private int toPort;
    private String toIP;

    public TalkSender(int fromPort, int toPort, String toIP) {
        this.fromPort = fromPort;
        this.toPort = toPort;
        this.toIP = toIP;
        try{
            socket=new DatagramSocket(fromPort);
            reader=new BufferedReader(new InputStreamReader(System.in));
        }catch(Exception e){
            e.printStackTrace();
        }
    }

    @Override
    public void run() {
        while(true){
            try {
                String data = reader.readLine();
                byte[] datas = data.getBytes();
                DatagramPacket packet = new DatagramPacket(datas, 0, datas.length, new InetSocketAddress("localhost", 6666));
                // 3. send the packet
                socket.send(packet);
                if (data.equals("exit")) {
                    break;
                }
            }catch(Exception e){
                e.printStackTrace();
            }
        }
        // 4. close
        socket.close();
    }
}
